import axios from "axios";
import Cookies from "js-cookie"
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

const service = axios.create({
    baseURL:"http://localhost:5173/api/api",
    timeout:10*1000
});

service.interceptors.request.use((config:any)=>{
    if (config.headers.isToken){
        //添加token到请求头
        if (Cookies.get("Admin-Token")){
            config.headers.Authorization = Cookies.get("Admin-Token")
        }else {
            ElMessage.warning("登录已过期，请重新登录")
            return
        }
    }
    return config
})

service.interceptors.response.use((res)=>{
    const {data} = res
    // 对不同的状态码做统一返回值处理
    if (data.code >= 200 && data.code < 300){
        return data
    }
    if (data.code === 401){

        ElMessage.warning("登录已过期，请重新登录")
    }
    if (data.code === 500){
        ElMessage.error("服务器发生错误")
    }
})

export default service;
